//index.js
//获取应用实例
var app = getApp();
var time_box = '';
Page({
  data: {
    images: {},
    title: {}, //头部红色区域显示的说明性文字
    urlimg: app.urlimg,
    // 订单状态
    orderStatus: null,
    data: {},
    freight: true,
    isHide: false,
    //订单代付款倒计时
    countdown: '',
  },
  imageLoad: function (e) {
    var $width = e.detail.width,    //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 718,           //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 718 / ratio;    //计算的高度值
    var image = this.data.images;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image[e.target.dataset.index] = {
      width: viewWidth,
      height: viewHeight
    }
    console.log(image);
    this.setData({
      images: image
    })
  },
  swiperItem: function (e) {
    var that = this;
    // 页面跳转
    if (e.currentTarget.dataset.url != '') {
      wx.navigateTo({
        url: e.currentTarget.dataset.url,
      })
    }
  },
  //复制按钮
  copy_btn: function () {
    console.log('复制运单编号');
    var that = this;
    wx.setClipboardData({
      data: that.data.data.order_no,
      success: function (res) {
        console.log(res);
        wx.getClipboardData({
          success: function (res) {
            console.log(res.data) // data
            //提示信息
            wx.showToast({
              title: '复制成功',
              icon: 'success',
              duration: 1000,
            })
          }
        })
      }
    })
  },
  //延长收货
  extend_receipt: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '每张订单延长收货只能申请一次，延长收货时间为5天。',
      success: function (res) {
        if (res.confirm) {
          console.log('获取订单id为：' + e.currentTarget.id);
          wx.request({
            url: app.url + 'api_order/extendTime',
            data: { orderId: e.currentTarget.id },
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token_key')
            },
            success: function (res) {
              var all_box = that.data.data;
              for (var i = 0; i < all_box.length; i++) {
                if (all_box[i].id == e.currentTarget.id) {
                  all_box[i].is_extend = 1;
                }
              }
              that.setData({
                data: all_box,
              })
              //提示信息
              wx.showToast({
                title: '成功延长收货',
                icon: 'success',
                duration: 1500,
              })
            },
          })
        }
      }
    })
  },
  onLoad: function (e) {
    var that = this;
    console.log(e)

    var token_key = wx.getStorageSync('token_key');
    console.log(token_key);

    if (token_key == undefined || token_key == '') {
      app.getUserInfo(function () {
        load_fn();
      })
    } else {
      load_fn()
    }


    function load_fn() {

      // 订单请求
      that.getData(e.id);

      //猜你喜欢（引用“我的收藏”）
      wx.request({
        url: app.url + 'api_goods/get_favoriteV1',
        data: {
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        }, success: function (json) {
          var selectGoodsImgs = [];
          for (var i = 0; i < json.data.result.favorite_goods.length; i++) {
            selectGoodsImgs.push(
              "/pages/icon/checkMsg.png"
            )
          }
          that.setData({
            likegoods: json.data.result.likegoods,
          });
          console.log(that.data);
        }
      })

    }
  },
  //查看物流信息
  show_delivery_btn: function (e) {
    if (e.currentTarget.dataset.type == 2) {
      //多条快递信息
      wx.redirectTo({ url: '/pages/account/order/logistics/index?id=' + e.currentTarget.id, })
    } else {
      wx.navigateTo({ url: '/pages/account/logistics/index?order_id=' + e.currentTarget.id + '&id=0', })
    }
  },
  //订单信息请求
  getData: function (id) {
    var that = this;
    wx.request({
      url: app.url + 'api_user/order_detail',
      data: {
        id: id,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      }, success: function (json) {

        if (json.data.done) {

          // 活动优惠金额的显示
          if (json.data.result.couponMoney == 0 || json.data.result.is_imitate!=1) {
            json.data.result.couponMoney = Number(json.data.result.couponMoney).toFixed(2);
          }

          that.setData({ data: json.data.result, orderStatus: json.data.result.orderStatus, })

          //判断订单状态
          order_status(that.data.data, that);
          // 物流信息请求
          that.logistics(id);
        } else {
          wx.showModal({
            title: '提示',
            content: json.data.message,
          })
        }
      }
    })
  },
  // 物流请求
  logistics: function (id) {
    var that = this;
    var timeout = '';
    timeout = setTimeout(function () {
      var freight = {};
      freight.result = "success";
      freight.data = [];
      freight.data[0] = {};
      freight.data[0].station = "抱歉，暂时无法请求物流信息，请稍后重试。";
      that.setData({
        'data.freight': freight,
      })
    }, 5000);
    wx.request({
      url: app.url + 'api_user/order_freight',
      data: {
        id: id,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      success: function (res) {
        clearTimeout(timeout);
        timeout = '';
        that.setData({
          'data.freight': res.data.result.freight,
        })

      },
    })

  },
	/**
		* 查看中奖详情
		*/
  prizeTap: function (e) {
    var order_id = e.currentTarget.dataset.order_id
    if (order_id > 0) {
      wx.navigateTo({
        url: '/pages/mygroup/winning/winning?orderId=' + order_id,
      })
    }
  },
  //删除订单
  delete_order: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '订单删除后不可恢复，确认删除吗？',
      success: function (res) {
        if (res.confirm) {
          //console.log('订单编号：' + e.currentTarget.dataset.order_id);
          wx.request({
            url: app.url + 'api_user/DelOrder',
            data: {
              order_id: e.currentTarget.dataset.order_id,
              op: 'confirm'
            },
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token_key')
            }, success: function (json) {
              if (json.data.done == true) {
                that.getData(e.currentTarget.dataset.id, wx.getStorageSync('token_key'));
                wx.navigateBack({ delta: '' })
              } else {
                wx.showModal({
                  title: '提示',
                  content: json.data.message,
                })
              }
            }
          })

        }
      }
    })
  },
  //确认收货
  sure_goods: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '请收到货后，再确认收货！',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.url + 'api_user/order_status',
            data: {
              order_id: e.currentTarget.dataset.id,
              op: 'confirm'
            },
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token_key')
            }, success: function (json) {
              if (json.data.done == true) {
                that.getData(e.currentTarget.dataset.id, wx.getStorageSync('token_key'));
              } else {
                wx.showModal({
                  title: '提示',
                  content: json.data.message,
                })
              }
            }
          })
        }
      }
    })
  },

  //猜你喜欢，查看商品详情
  click_goods: function (e) {
    console.log(e.currentTarget.id);
    wx.redirectTo({
      url: '/pages/index/detail/index?id=' + e.currentTarget.id,
    })
  },
  // 获得毫秒数  转化  成小时、分钟、秒
  time: function (Time) {
    var that = this;
    Time -= 1;
    var hours = parseInt(Time / 60 / 60 % 24, 10); //计算剩余的小时 
    if (('' + hours).length == 1) {
      hours = '0' + hours;
    }
    var minutes = parseInt(Time / 60 % 60, 10);//计算剩余的分钟 
    if (('' + minutes).length == 1) {
      minutes = '0' + minutes;
    }
    var seconds = parseInt(Time % 60, 10);//计算剩余的秒数 
    if (('' + seconds).length == 1) {
      seconds = '0' + seconds;
    }
    var times = hours + "小时" + minutes + "分" + seconds + "秒";//排列时间

    // console.log(times);
    that.setData({
      countdown: times,
    })
  },

  //取消订单
  cancel_order: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定取消订单？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.url + 'api_user/order_status',
            data: {
              order_id: e.currentTarget.id,
              op: 'cancel'
            },
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token_key')
            }, success: function (json) {
              if (json.data.done == true) {
                that.setData({ orderStatus: 5 })
              } else {
                wx.showModal({
                  title: '提示',
                  content: json.data.message,
                })
              }
            }
          })
        }
      }
    })




  },
  //退款申请
  refunds: function (e) {
    // wx.showModal({
    //   title: '提示',
    //   content: '由于系统升级，请联系在线客服处理退款。',
    //   success: function (res) {
    //     if (res.confirm) {
    //       console.log('用户点击确定')
    //     }
    //   }
    // })
    var that = this;
    if (that.data.data.str_completion_time) {
        var now = Date.parse(new Date()) / 1000;
        var temp = that.data.data.str_completion_time + 30 * 86400;
        if (now > temp) {
            wx.showModal({
                title: '提示',
                content: '因收货时间较长，不支持申请售后，有问题请联系在线客服',
                success: function (res) {
                    wx.redirectTo({
                        url: '/pages/index/index',
                    })
                }
            })
        } else {
            wx.redirectTo({
                url: '/pages/account/refund/index?order_goods_id='
                + e.currentTarget.dataset.id + '&order_id='
                + e.currentTarget.dataset.order_id
            })
        }
    } else {
        wx.redirectTo({
            url: '/pages/account/refund/index?order_goods_id='
            + e.currentTarget.dataset.id + '&order_id='
            + e.currentTarget.dataset.order_id
        })
    }

  },
  bindFormSubmit: function (e) {
    if (e.detail.value.kd_no.length < 5) {
      wx.showModal({
        title: '提示',
        content: '快递单号格式不正确',
        success: function (res) {
          if (res.confirm) {

          }
        }
      })
      return
    }

    wx.request({
      url: app.url + 'api_user/refund_kdno',
      data: {
        id: this.data.data.refundment_doc.id,
        kd_no: e.detail.value.kd_no
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      }, success: function (json) {
        if (json.data.done == false) {
          wx.showModal({
            title: '提示',
            content: json.data.message,
            success: function (res) {
              if (res.confirm) {

              }
            }
          })

        } else {
          wx.showModal({
            title: '提示',
            content: json.data.result,
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/account/order/index?pid=0'
                })
              }
            }
          })

        }

      }
    })
  }
  ,

  toPay: function (e) {

    var that = this
    console.log(that.data.data.goods_id)
    wx.request({
      url: app.url + 'api_order/goPay',
      data: {
        order_id: that.data.data.id,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      }, success: function (json) {
        console.log(json)
        if (json.data.done) {
          wx.requestPayment({
            'appId': json.data.result.appid,
            'timeStamp': json.data.result.timeStamp.toString(),
            'nonceStr': json.data.result.nonceStr,
            'package': json.data.result.package,
            'signType': 'MD5',
            'paySign': json.data.result.sign,
            'success': function (res) {
              console.log(res);
              console.log('success');
              wx.redirectTo({
                url: '/pages/account/succeed/index?orderId=' + json.data.result.orderId,
              })

            },
            'fail': function (res) {
              wx.showToast({
                title: '支付失败！',
                image: '/pages/icon/delete.png',
                duration: 1200,
                mask: true,
                complete: function () {
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/account/order/index',
                    })
                  }, 1200)
                } //接口调用结束的回调函数  
              })
            },
            'complete': function (res) {
              console.log(res); console.log('complete');
            }
          })
          // that.setData({'data':json.data.result})
        } else {
          var msg = json.data.message;
          wx.showModal({
            title: '提示',
            content: msg,
            success: function (res) {
            }
          })
        }
      }
    })



  }, postscript: function (e) {
    this.data.postscript = e.detail.value
    console.log(this.data.postscript)
  },
  freight: function (e) {
		/*this.setData({
			'freight': false
		})*/
    wx.redirectTo({
      url: '/pages/account/logistics/index?id=' + e.currentTarget.id,
    })

  },
  modalOk: function (e) {
    this.setData({
      'freight': true
    })
  }
  ,
  goodslink: function (e) {
    var that = this;
    console.log(that.data.data);
    console.log(that.data.data.action_type);
    var url = '';
    if (that.data.data.action_type != 0 && that.data.data.action_type != 1 && that.data.data.action_type != 2) {
      url = '/pages/group/groupdetail/index?id=' + that.data.data.goods[0].goods_id + '&regiment_id=' + that.data.data.goods[0].goods_id + '&group_type=' + that.data.data.goods[0].goods_type;
    } else {
      url = '/pages/index/detail/index?id=' + e.currentTarget.id;
    }
    wx.redirectTo({
      url: url,
    })
  },
  // 添加收货人信息
  addAddressTAP: function () {
    if (this.data.persion != null) {
      wx.showModal({
        title: '提示',
        content: '确定要修改联系人信息么？',
        confirmText: "确定",
        success: function (res) {
          if (res.confirm) {

            wx.navigateTo({
              url: './addressMsg/index',
            })
          }
        }
      })
    }
    else {
      wx.navigateTo({
        url: './addressMsg/index',
      })

    }
  },
  onShow: function () {
    var that = this;
    time_box = setInterval(function () {
      if (that.data.data.orderStatus == 2) {
        if (time_computations(that.data.data.str_create_time, that) != false) {
          var min_title = '若' + time_computations(that.data.data.str_create_time, that) + '内未付款，订单自动取消';
        } else {
          var min_title = '抱歉，您未在规定时间内付款，订单已自动取消';
          clearInterval(time_box);
          time_box = '';
        }
      } else if (that.data.data.orderStatus == 3 || that.data.data.orderStatus == 8 || that.data.data.orderStatus == 11 || that.data.data.orderStatus == 15) {
        if (time_computations(that.data.data.distance_accept_time, that) != false) {
          var min_title = '距离自动确认收货还剩' + time_computations(that.data.data.distance_accept_time, that);
        } else {
          var min_title = '10天内买家未确认收货，系统将自动确认收货';
        }
      } else {
        clearInterval(time_box);
        time_box = '';
      }
      that.setData({
        'title.min_title': min_title,
      })
    }, 1000)
  },
	/**
 * 生命周期函数--监听页面隐藏
 */
  onHide: function () {
    clearInterval(time_box);
  },

	/**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function () {
    clearInterval(time_box);
  },
  //分享
  onShareAppMessage: function () {

  },
})


//判断订单状态
function order_status(data, aaa) {
  console.log(data)
  // json.data.result.status = 1;//订单状态——状态码
  console.log("订单状态" + data.orderStatus);


  var orderStatus = data.orderStatus; //订单状态说明:0未知 1等待发货（货到付款） 2等待付款（线上支付） 3已发货（已付款） 4等待发货 5已取消 6已完成 7已退款 8部分发货（不需要付款） 9部分退款（未发货+部分退款） 10部分退款（已发货） 11已发货（未付款） 12申请退款 13待成团 14拼团成功，等待发货 15拼团成功，已经发货 16拼团成功，待开奖 17拼团成功，已开奖 18拼团失败，退款中 19拼团失败，退款完成
  var title = {};   //对应 data.title字段

  var img_style01 = 'width:65px;height:45px;top:12px;';
  var img_style02 = 'width:58px;height:56px;';
  var img_style03 = 'width:62px;height: 60px;top:6px;';
  var img_style04 = 'width: 74px;height: 74px;top: 0px;';
  switch (parseInt(orderStatus)) {
    case 0://0未知
      title = {
        max_title: '订单异常',
        min_title: '异常订单，请联系客服',
        img: '/pages/icon/pingtuan/04.png',
        img_style: img_style04,
      };
      break;
    case 1://1等待发货（货到付款）
      title = {
        max_title: '等待卖家发货',
        min_title: '仓库正为您的商品打包发货，请耐心等待',
        img: '/pages/icon/pingtuan/04.png',
        img_style: img_style04,
      };
      break;
    case 2://2等待付款（线上支付）
      data.str_create_time += 86400;
      if (time_computations(data.str_create_time, aaa) != false) {
        var min_title = '若' + time_computations(data.str_create_time, aaa) + '内未付款，订单自动取消';
      } else {
        var min_title = '抱歉，您未在规定时间内付款，订单已自动取消';
      }
      title = {
        max_title: '等待买家付款',
        min_title: min_title,
        img: '/pages/icon/pingtuan/04.png',
        img_style: img_style04,
      };
      break;
    case 3://3已发货（已付款）			
      if (time_computations(data.distance_accept_time, aaa) != false) {
        var min_title = '距离自动确认收货还剩' + time_computations(data.distance_accept_time, aaa);
      } else {
        var min_title = '10天内买家未确认收货，系统将自动确认收货';
      }
      title = {
        max_title: '已发货,等待买家确认收货',
        min_title: min_title,
        img: '/pages/icon/pingtuan/01.png',
        img_style: img_style01,
      };
      break;
    case 4://4等待发货
      title = {
        max_title: '支付成功，等待卖家发货',
        min_title: '仓库正为您的商品打包发货，请耐心等待',
        img: '/pages/icon/pingtuan/04.png',
        img_style: img_style04,
      };
      break;
    case 5://5已取消
      title = {
        max_title: '取消订单',
        min_title: '订单已取消，交易已关闭',
        img: '/pages/icon/pingtuan/05.png',
        img_style: 'width:54px;height: 50px;top:8px;',
      };
      break;
    case 6://6已完成
      title = {
        max_title: '交易成功',
        min_title: '',
        img: '/pages/icon/pingtuan/02.png',
        img_style: img_style02 + 'top:-6px;',
      };
      break;
    case 7://7已退款
      title = {
        max_title: '退款完成',
        min_title: '款项已原路返回了哦，请查收',
        img: '/pages/icon/pingtuan/03.png',
        img_style: img_style03,

      };
      break;
    case 8://8部分发货（不需要付款）			
      if (time_computations(data.distance_accept_time, aaa) != false) {
        var min_title = '距离自动确认收货还剩' + time_computations(data.distance_accept_time, aaa);
      } else {
        var min_title = '10天内买家未确认收货，系统将自动确认收货';
      }
      title = {
        max_title: '已发货，等待买家确认收货',
        min_title: min_title,
        img: '/pages/icon/pingtuan/01.png',
        img_style: img_style01,
      };
      break;
    case 9://9部分退款（未发货 + 部分退款）
      title = {
        max_title: '部分商品退款，等待卖家发货',
        min_title: '仓库正为您的商品打包发货，请耐心等待',
        img: '/pages/icon/pingtuan/03.png',
        img_style: img_style03,
      };
      break;
    case 10://10部分退款（已发货）
      title = {
        max_title: '部分商品退款，等待买家确认收货',
        min_title: '10天内买家未确认收货，系统将自动确认收货',
        img: '/pages/icon/pingtuan/01.png',
        img_style: img_style01,
      };
      break;
    case 11://11已发货（未付款）
      if (time_computations(data.distance_accept_time, aaa) != false) {
        var min_title = '距离自动确认收货还剩' + time_computations(data.distance_accept_time, aaa);
      } else {
        var min_title = '10天内买家未确认收货，系统将自动确认收货';
      }
      title = {
        max_title: '已发货，等待买家确认收货',
        min_title: min_title,
        img: '/pages/icon/pingtuan/01.png',
        img_style: img_style01,
      };
      break;
    case 12://12申请退款
      title = {
        max_title: '申请退款',
        min_title: '预计1-7个工作日内处理退款',
        img: '/pages/icon/pingtuan/03.png',
        img_style: img_style03,
      };
      break;
    case 13: //13待成团
      title = {
        max_title: '拼团还未成功',
        min_title: '让小伙伴们都来拼团吧~',
        img: '/pages/icon/pingtuan/04.png',
        img_style: img_style04,
      };
      break;
    case 14://14拼团成功，等待发货
      title = {
        max_title: '拼团成功，等待卖家发货',
        min_title: '仓库正为您的商品打包发货，请耐心等待',
        img: '/pages/icon/pingtuan/04.png',
        img_style: img_style04,
      };
      break;
    case 15://15拼团成功，已经发货
      console.log(data);
      if (time_computations(data.distance_accept_time, aaa) != false) {
        console.log();
        var min_title = '距离自动确认收货还剩' + time_computations(data.distance_accept_time, aaa);
      } else {
        var min_title = '10天内买家未确认收货，系统将自动确认收货';
      }
      title = {
        max_title: '已发货，等待确认收货',
        min_title: min_title,
        img: '/pages/icon/pingtuan/01.png',
        img_style: img_style01,
      };
      break;
    case 16://16拼团成功，待开奖
      title = {
        max_title: '拼团成功，等待开奖',
        min_title: '拼团成功，请耐心等待开奖~',
        img: '/pages/icon/pingtuan/04.png',
        img_style: img_style04,
      };
      break;
    case 17://17拼团成功，已开奖
      var prize = data.prize;
      var min_title = '';
      if (prize == 1) {
        min_title = '恭喜，已中一等奖，大奖马上到！';
      } else if (prize == 2) {
        min_title = '抱歉，没中奖哦。即将安排退款再送你专属劵';
      } else if (prize == 3) {
        min_title = '恭喜，已中二等奖，即将安排退款并送礼品！';
      }
      title = {
        max_title: '拼团成功，已开奖',
        min_title: min_title,
        img: '/pages/icon/pingtuan/02.png',
        img_style: img_style02 + 'top:5px;',
      };
      break;
    case 18://18拼团失败，退款中
      title = {
        max_title: '拼团失败，退款中',
        min_title: '预计1-7个工作日内处理退款',
        img: '/pages/icon/pingtuan/03.png',
        img_style: img_style03,
      };
      break;
    case 19://19拼团失败，退款完成
      title = {
        max_title: '拼团失败，退款完成',
        min_title: '款项已原路返回了哦，请查收',
        img: '/pages/icon/pingtuan/03.png',
        img_style: img_style03,
      };
      break;
    default:
      break;
  }

  aaa.setData({ title: title, })
}



//倒计时计算
function time_computations(Time, that) {
  var current_time = Date.parse(new Date()) / 1000;
  // console.log("获取当前时间" + current_time);
  var time_text = ''; 1512032915
  if (current_time < Time) {
    var Times = Time - current_time;
    --Times;

    var day = Math.floor(Times / (60 * 60 * 24));//计算剩余的天数
    if (('' + day).length == 1) {
      day = '0' + day;
    }
    var hours = parseInt(Times / 60 / 60 % 24, 10); //计算剩余的小时
    if (('' + hours).length == 1) {
      hours = '0' + hours;
    }
    var minutes = parseInt(Times / 60 % 60, 10);//计算剩余的分钟
    if (('' + minutes).length == 1) {
      minutes = '0' + minutes;
    }
    var seconds = parseInt(Times % 60, 10);//计算剩余的秒数
    if (('' + seconds).length == 1) {
      seconds = '0' + seconds;
    }
    //倒计时判断
    if (that.data.data.orderStatus == 2) {//待支付时显示的时间
      return time_text = hours + "小时" + minutes + "分" + seconds + "秒";
    } else if (that.data.data.orderStatus == 3 || that.data.data.orderStatus == 8 || that.data.data.orderStatus == 11 || that.data.data.orderStatus == 15) {//待收货时显示的时间
      return time_text = day + "天" + hours + "小时";
    }
  } else {
    return false;
  }
}